package org.example.service.client;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;
import org.example.HelloServiceGrpc;
import org.example.helloProto;

import java.util.concurrent.TimeUnit;

/**
 * @Author : 叶荻风
 * @create : 2024/6/21 15:33
 */
public class GrpcClientCS2SS {
    public static void main(String[] args) {
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost",9000).usePlaintext().build();
        HelloServiceGrpc.HelloServiceStub helloServiceStub = HelloServiceGrpc.newStub(managedChannel);
        StreamObserver<helloProto.HelloRequest> requestStreamObserver =
                helloServiceStub.cs2ss(new StreamObserver<helloProto.HelloResponse>() {
            @Override
            public void onNext(helloProto.HelloResponse value) {
                System.out.println("接受到server内容"+value.getUsername());
            }

            @Override
            public void onError(Throwable t) {

            }

            @Override
            public void onCompleted() {
                System.out.println("响应全部结束");
            }
        });
        for (int i = 0; i < 10; i++) {
            requestStreamObserver.onNext(helloProto.HelloRequest.newBuilder().setUsername("difeng"+i).build());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        requestStreamObserver.onCompleted();

        try {
            managedChannel.awaitTermination(50, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        managedChannel.shutdown();

    }
}
